package com.listing.action;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.quartz.SchedulerException;

import com.listing.service.ListingEngine;
import com.listing.service.ListingService;
import com.listing.service.TaobaoService;
import com.taobao.api.domain.Item;

@Results({
	  @Result(name="success", type="httpheader", params={"headers.msg", "ok"}),
	  @Result(name="overflow", type="httpheader", params={"headers.msg", "overflow"})
})
public class WellDistributeAllAction extends ActionBase{

	private int fromHour = 9;
	private int toHour = 23;
	
	public String execute() throws Exception
	{
		long userId = getUserId();
		String session = getSessionId();
		String version = getVersion();
		TaobaoService service = new TaobaoService();
		List<Item> items = service.getAllOnsaleItems(session);
		if (items != null)
		{
			int allItemsCount = items.size();
			if (ListingService.INSTANCE.isOverflow(userId, version, allItemsCount))
			{
				_log.info("jobs overflow!");
				return "overflow";
			}
			int hours = toHour - fromHour;
			double itemsCountPerDayDouble = allItemsCount / 7f;
			int itemsCountPerDay = (int)Math.round(itemsCountPerDayDouble);
			int interval = (int)Math.round(60 * hours / itemsCountPerDayDouble);
			_log.info("interval: " + interval);
			ListingEngine engine = new ListingEngine(userId);
			for (int i = 0; i < itemsCountPerDay; i++)
			{
				long offset = interval * i;
				long hour = fromHour + offset / 60;
				long minute = offset % 60;
				for (int j = 0; j < 7; j++)
				{
					int index = 7 * i + j;
					if (index >= items.size())
					{
						break;
					}
					Item item = items.get(index);
					if (!item.getIsVirtual())
					{
						long numIid = item.getNumIid();
						String topSession = getSessionId();
						Calendar cld = Calendar.getInstance();
						cld.setTime(item.getListTime());
						int dayOfWeek = j + 1;
						cld.set(Calendar.DAY_OF_WEEK, dayOfWeek);
						cld.set(Calendar.HOUR_OF_DAY, (int)hour);
						cld.set(Calendar.MINUTE, (int)minute);
						Date newListTime = cld.getTime();
						while (newListTime.before(new Date()))
						{
							_log.info("add week period to make time after now.");
							cld.add(Calendar.DATE, 7);
							newListTime = cld.getTime();
						}
						try {
							if (engine.jobExists(numIid))
							{
								engine.remove(numIid);
							}
							engine.list(numIid, newListTime, topSession);
						} catch (SchedulerException e) {
							error(e);
						}
					}
				}
			}
		}
		return SUCCESS;
	}
}
